<template>
  <div class="app-container">
    <div>
      <el-button
        size="mini"
        type="primary" icon="el-icon-zoom-in"
        @click="$refs.table.OpenAll()"
      >展开所有</el-button>
      <el-button
        size="mini"
        type="primary" icon="el-icon-zoom-out"
        @click="$refs.table.ZipAll()"
      >收缩所有</el-button>
      <el-button
        size="mini"
        type="primary" icon="el-icon-plus"
        @click="handleCreate({id:0})"
      >添加一级菜单</el-button>
      <el-button
        size="mini"
        type="primary" icon="el-icon-plus"
        @click="handleCopyMenu({id:0})"
      >批量发布一级菜单</el-button>
    </div>

    <dragTreeTable
      ref="table"
      :data="tableData"
      style="width: 100%"
      row-key="id"
      border
      lazy
      hightRowChange
      :onDrag="onTreeDataChange"
      v-loading="menuLoading"
    />


    <el-dialog :title="textMap[dialogStatus]" :close-on-click-modal="false" :visible.sync="dialogFormVisible" width="800px">
      <el-form ref="dataForm" :model="temp" label-position="left" label-width="150px" style="width: 100%; padding: 0 30px;">
        <el-form-item label="菜单名称" prop="title">
          <el-input v-model="temp.name" />
        </el-form-item>
        <el-form-item label="组件名称" prop="title">
          <el-input v-model="temp.nameEn" />
        </el-form-item>
        <el-form-item label="组件地址" prop="title">
          <el-input v-model="temp.url" />
        </el-form-item>
        <el-form-item label="权限值" prop="title">
          <!--<el-input v-model="temp.auth" />-->
          <el-input type="textarea" autosize v-model="temp.auth" />
        </el-form-item>
        <el-form-item label="图标" prop="title">
          <el-input v-model="temp.iconClass" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          保存
        </el-button>
      </div>
    </el-dialog>


    <el-dialog title="菜单结构-复制/发布" :close-on-click-modal="false" :visible.sync="dialogFormVisible4CopyMenu">
      <div class = "routeManagement">
        <vue-json-editor v-model="menuJson" mode="code" :show-btns="false" :exapndedOnStart="true" lang="zh"/>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible4CopyMenu = false">
          关闭
        </el-button>
        <el-button type="primary" plain
                v-clipboard:copy="JSON.stringify(menuJson)"
                v-clipboard:success="onJsonCopySuccess"
                v-clipboard:error="onJsonCopyError">
          复制
        </el-button>
        <el-button type="primary" plain @click="menuJson={} ">
          清空
        </el-button>

        <el-button type="primary" @click="onJsonSave">
          发布
        </el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>

import { getAuthsTree, addeditAuthNode, delAuthNode, batchUpdateMenusSort, publishMenu } from './api/auth'
import dragTreeTable from 'drag-tree-table'
import vueJsonEditor from 'vue-json-editor'


export default {
  name: 'AuthList',
  components: {
    dragTreeTable, vueJsonEditor
  },
  data() {
    return {
      menuLoading: false,
      tableData: {
        custom_field: {
          id: 'id',
          order: 'sort',
          lists: 'children',
          parent_id: 'menuParentId'
        },
        lists:[],
        columns: [
          {
            type: 'selection',
            title: '菜单名称',
            field: 'name',
            width: 250,
            align: 'left',
            formatter: (item) => {
              return '<a>'+item.name+'</a>'
            }
          },
          {
            title: '组件名称/权限值',
            field: 'nameEnOrAuth',
            width: 250,
            align: 'left',
            formatter: (item) => {
              return '<a>'+item.nameEn+item.auth+'</a>'
            }
          },
          {
            title: '组件链接',
            field: 'url',
            width: 300,
            align: 'left'
          },
          {
            title: '图标',
            field: 'iconClass',
            width: 100,
            align: 'left'
          },
          {
            title: '操作',
            type: 'action',
            width: 190,
            align: 'center',
            actions: [
              {
                text: '添加',
                onclick: this.handleCreate,
                formatter: (item) => {
                  if (item.auth !== undefined && item.auth !==''){
                    return '<a href="#" class="myDisabled">添加</a>'
                  }else {
                    return '<a href="#" class="myButton">添加</a>'
                  }
                }
              },
              {
                text: '编辑',
                onclick: this.handleEdit,
                formatter: (item) => {
                  return '<a href="#" class="myButton" style="margin-left: 3px;">编辑</a>'
                }
              },
              {
                text: '删除',
                onclick: this.handleDelete,
                formatter: (item) => {
                  return '<a href="#" class="myButton" style="margin-left: 3px;">删除</a>'
                }
              }
            ]
          },
          {
            title: '发布',
            type: 'action',
            width: 100,
            align: 'center',
            actions: [
              {
                text: '复制/发布',
                onclick: this.handleCopyMenu,
                formatter: (item) => {
                  return '<a href="#" class="myButton">复制/发布</a>'
                }
              }
            ]
          }
        ]
      },
      search: '',
      dialogFormVisible: false,
      index: -1,
      temp: {
        id: undefined,
        name: '',
        auth: ''
      },
      dialogStatus: '',
      textMap: {
        update: '编辑框',
        create: '新增框'
      },
      pid: undefined,
      // copy menu
      dialogFormVisible4CopyMenu: false,
      menuJson: {},
      pId: 0

    }
  },
  mounted() {
      //
      this.fetchData()
  },
  methods: {
    fetchData() {
        this.menuLoading = true
        getAuthsTree().then(result => {
            this.tableData.lists = result.map.list
            // console.log(this.tableData.lists)
            this.menuLoading = false
        })
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        name: '',
        auth: '',
        url: '',
        nameEn: ''
      }
    },
    // Create
    handleCreate(row) {
      if (row.auth !== undefined && row.auth !==''){
        return
      }

      this.resetTemp()

      this.pid = row.id
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
    },
    createData() {
      const tempData = Object.assign({}, this.temp)
      tempData.optType = 'add'
      tempData.pid = this.pid
      tempData.text = tempData.name
      addeditAuthNode(tempData).then((r) => {
        this.notify(r)
        if (r.success) {
          this.dialogFormVisible = false
          tempData.id = r.obj.id
          if (tempData.pid === 0) {
            // Root
            this.tableData.lists.push(tempData)
          } else {
            this.$refs.table.AddRow(tempData.pid, tempData)
          }
        }
      })
    },

    // Update
    handleEdit(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
    },
    updateData() {
      const tempData = Object.assign({}, this.temp)
      tempData.children = undefined
      tempData.optType = 'edit'
      tempData.text = tempData.name
      addeditAuthNode(tempData).then((r) => {
        this.notify(r)
        if (r.success) {
          this.dialogFormVisible = false
          this.$refs.table.EditRow(tempData.id, tempData)
        }
      })
    },

    handleDelete(row) {
        this.$confirm('确认删除吗？')
            .then(_ => {
                // delete api
                delAuthNode({ id: '' + row.id }).then((r) => {
                    this.notify(r)
                    if (r.success) {
                        const updatedLists = this.$refs.table.DelById(row.id)
                        this.tableData.lists = updatedLists;
                        // this.delForEach(this.tableData.lists, row.id)
                    }
                })
                // end
            })
            .catch(_ => {})
    },

    //
    onTreeDataChange(lists) {
      // console.log(lists)
      this.tableData.lists = lists

      const myLists = []
      this.dragForEach(lists, myLists)

      batchUpdateMenusSort({'jsonListStr':JSON.stringify(myLists)}).then(r => {
        if (r.success) {
          this.notify(r, '位置调整成功')
        }
      })
    },
    dragForEach(lists, myLists) {
      if (lists === undefined) {
        return true
      }
      lists.forEach((item, i) => {
        const myItem = {}
        myItem.id = item.id
        myItem.sort = item.sort
        myItem.menuParentId = item.menuParentId
        myLists.push(myItem)

        this.dragForEach(item.children, myLists)
      })
    },
    // copy menu
    handleCopyMenu(row) {
      this.dialogFormVisible4CopyMenu = true
      this.menuJson = row
      this.pId = row.id
    },
    onJsonCopySuccess () {
      this.$message({
        message: '复制成功，请粘贴到目标节点发布',
        type: 'success'
      });
    },
    onJsonCopyError () {
      this.$message.error("复制失败");
    },
    onJsonSave () {
      // 保存时，当前node是父node, this.menuJson是子node内容
      // console.log('this.menuJson:', this.menuJson)
      // console.log('this.pId:', this.pId)
      const data = {}
      data.pId = this.pId
      data.menuJson = this.menuJson

      publishMenu(data).then( r => {
        this.notify(r)
        if (r.success) {
          this.dialogFormVisible4CopyMenu = false
        }
      })
    },
  }
}
</script>



<style>
  .drag-tree-table-body {
    font-size: 14px;
  }
  .drag-tree-table-header{
    font-size: 14px;
    height: 50px;
    line-height: 30px;
  }
  .tree-row {
    height: 50px;
  }

  .myButton {
    background:linear-gradient(to bottom, #77b55a 5%, #72b352 100%);
    background-color:#77b55a;
    border-radius:4px;
    border:1px solid #4b8f29;
    display:inline-block;
    cursor:pointer;
    color:#ffffff;
    font-family:Arial;
    font-size:7px;
    font-weight:bold;
    padding:5px 10px;
    text-decoration:none;
    text-shadow:0px 1px 0px #5b8a3c;
    line-height: 15px;
  }
  .myButton:hover {
    background:linear-gradient(to bottom, #72b352 5%, #77b55a 100%);
    background-color:#72b352;
    color:#dddddd;
  }
  .myButton:active {
    position:relative;
    color:#ffffff;
    top:1px;
  }
  .myButton:visited{color:#ffffff;}
  /*.myButton:link{color:#555555;}*/

  .myDisabled {
    background:linear-gradient(to bottom, gray 5%, gray 100%);
    background-color:#ccc;
    border-radius:4px;
    border:1px solid gray;
    display:inline-block;
    cursor:pointer;
    color:#ccc;
    font-family:Arial;
    font-size:7px;
    font-weight:bold;
    padding:5px 10px;
    text-decoration:none;
    line-height: 15px;
  }
  .myDisabled:link {
    background-color:#aaa;
    color:#ccc;
  }
  .myDisabled:hover {
    background:linear-gradient(to bottom, gray 5%, gray 100%);
    background-color:#aaa;
    color:#ccc;
  }
  .myDisabled:active {
    position:relative;
    color:#ccc;
    top:0px;
  }
  .myDisabled:visited{color:#ccc;}

</style>

<style lang="scss" scoped>
  .routeManagement{
    width:98%;
    margin:16px auto;
    /deep/.jsoneditor-vue{
      height:500px;
    }
    /deep/.json-save-btn{
      cursor: pointer;
    }
  }
</style>
